#!/usr/bin/ruby
# -*- ruby -*-
#
# http://www.reddit.com/r/dailyprogrammer/comments/126905/10272012_challenge_108_intermediate_minesweeper/

require 'optparse'

width  = 10
height = 10
mines  = 10

OptionParser.new do |o|
    o.on("--width=WIDTH", Integer) { |width| }
    o.on("--height=HEIGHT", Integer) { |height| }
    o.on("--mines=MINES", Integer) { |mines| }
end.parse!

g = height.times.inject([]) { |r, i| r << Array.new(width, '0') }

mines.times.map { [rand(height), rand(width)] }.each { |y, x| g[y][x] = '#' }

(0 .. (g.size - 1)).each do |y|
    (0 .. (g[y].size - 1)).each do |x|
        next if g[y][x] == '#'

        count = 0

        [-1, 0, 1].each do |dy|
            [-1, 0, 1].each do |dx|
                next if dy == 0 && dx == 0
                l_y = y + dy
                l_x = x + dx

                count += 1 if (0 <= l_y && l_y < g.size) && (0 <= l_x && l_x < g[y].size) && g[l_y][l_x] == '#'
            end
        end

        g[y][x] = count.to_s
    end
end

puts (0 .. (g.size - 1)).map { |y| g[y].join(" ") }.join("\n")
